/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/

package soft.hb.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import soft.hb.R;
import soft.hb.model.CarConfig;
import soft.hb.model.ExhaustCheck;
import soft.hb.model.User;
import soft.hb.util.FileUtils;
import soft.hb.util.HttpRequest;
import soft.hb.view.view.HandWriteView;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.ui.CutPictureActivity;
import zuo.biao.library.ui.DatePickerWindow;
import zuo.biao.library.ui.SelectPictureActivity;
import zuo.biao.library.util.DataKeeper;
import zuo.biao.library.util.JSON;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.SettingUtil;
import zuo.biao.library.util.StringUtil;
import zuo.biao.library.util.TimeUtil;

/**
 * 机动车排气检测记录
 *
 * @author yuanweiwei
 */
public class ExhaustCheckActivity extends BaseActivity implements OnClickListener, OnHttpResponseListener, AlertDialog.OnDialogButtonClickListener  {
    public static final String TAG = "ExhaustCheckActivity";

    /**
     * 获取启动IndexActivity的intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, ExhaustCheckActivity.class);
    }


    @Override
    public Activity getActivity() {
        return this; //必须return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.exhaust_check_activity);
        intent = getIntent();
        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private EditText editCompany;        // 单位
    private EditText editCheckDate;        // 检测时间
    private EditText editCheckCompany;        // 受检单位
    private EditText editJurisdiction;        // 辖区
    private EditText editPlateNumber;        // 车牌号
    private EditText editModel;        // 厂牌型号
    private EditText editCreationDate;        // 上牌日期
    private EditText editMileage;        // 行驶里程
    private EditText editPurify;        // 净化措施
    private EditText editSmoke1;        // 烟度检测值1
    private EditText editSmoke2;        // 烟度检测值2
    private EditText editSmoke3;        // 烟度检测值3
    private EditText editSmoke4;        // 烟度检测值4
    private EditText editRBAvg;        // RB均值
    private EditText editKAvg;        // K均值
    private EditText editCheckAddress;        // 检测地点
    private EditText editInstrument;        // 仪器型号
    private EditText editMeter;        // 仪表编号
    private ImageView ivSign;        // 签字
    private EditText editTestingPerson;        // 检测人
    private EditText editReviewer;        // 复核人
    private EditText editAuditor;        // 审核人
    private EditText editCarType;        // 车辆类型
    private EditText editRemarks;    // 备注
    private ImageView ivSrivingLicense; //行驶证

    private ImageView ivPhoto1; //照片1
    //    private ImageView ivPhoto2; //照片2
//    private ImageView ivPhoto3; //照片3
    private HandWriteView handWriteView;


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initView() {//必须调用
        editCompany = findView(R.id.edit_company);
        editPlateNumber = findView(R.id.edit_plateNumber);
        editCheckCompany = findView(R.id.edit_checkCompany);
        editJurisdiction = findView(R.id.edit_jurisdiction);
        editPlateNumber = findView(R.id.edit_plateNumber);
        editModel = findView(R.id.edit_model);
        editCreationDate = findView(R.id.edit_creationDate);
        editCreationDate.setOnClickListener(this);

        editMileage = findView(R.id.edit_mileage);
        editPurify = findView(R.id.edit_purify);
        editPurify.setOnClickListener(this);
        editSmoke1 = findView(R.id.edit_smoke1);
        editSmoke2 = findView(R.id.edit_smoke2);
        editSmoke3 = findView(R.id.edit_smoke3);
        editSmoke4 = findView(R.id.edit_smoke4);
        editRBAvg = findView(R.id.edit_RBAvg);
        editKAvg = findView(R.id.edit_KAvg);
        editCheckDate = findView(R.id.edit_checkDate);
        editCheckAddress = findView(R.id.edit_checkAddress);
        editInstrument = findView(R.id.edit_instrument);
        editInstrument.setOnClickListener(this);
        editMeter = findView(R.id.edit_meter);
        editMeter.setOnClickListener(this);
        ivSign = findView(R.id.iv_sign);
        ivSign.setOnClickListener(this);
        editTestingPerson = findView(R.id.edit_testingPerson);
        editTestingPerson.setOnClickListener(this);
        editReviewer = findView(R.id.edit_reviewer);
        editReviewer.setOnClickListener(this);
        editAuditor = findView(R.id.edit_auditor);
        editAuditor.setOnClickListener(this);
        editCarType = findView(R.id.edit_carType);
        editCarType.setOnClickListener(this);
        editRemarks = findView(R.id.edit_remarks);
        findView(R.id.btn_submit).setOnClickListener(this);
        ivSrivingLicense = findView(R.id.iv_driving_license);
        ivSrivingLicense.setOnClickListener(this);

        ivPhoto1 = findView(R.id.iv_photo1);
        ivPhoto1.setOnClickListener(this);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(mAdapter = new UriAdapter());
        mAdapter.setOnItemClickListener(new UriAdapter.OnItemOnClickListener() {
            @Override
            public void onItemOnClick(View view, int pos) {
                showPopMenu(view, pos);
            }

            @Override
            public void onItemLongOnClick(View view, int pos) {
            }
        });

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    private static String[] CAR_TYPE = {"轻型", "中型", "重型"};
    private static String[] TOPBAR_COLOR_NAMES = null;

    private static String[] TOPBAR_MEASURES = null;
    private static String[] TOPBAR_MODEL = null;
    private static String[] TOPBAR_NUMBER = null;
    private static List<CarConfig> LIST_MEASURES = new ArrayList<>();
    private static List<CarConfig> LIST_MODEL = new ArrayList<>();
    private static List<CarConfig> LIST_NUMBER = new ArrayList<>();

    private static List<User> DATA_USER = new ArrayList<>();
    //机动车排气检测记录
    private static ExhaustCheck exhaustCheck = new ExhaustCheck();
    private static List<String> paths = new ArrayList<>();

    @Override
    public void initData() {//必须调用
        showProgressDialog(R.string.loading);
        HttpRequest.getUserList(0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                JSONObject jsonObject = JSON.parseObject(resultJson);
                JSONArray data = jsonObject == null ? null : jsonObject.getJSONArray("data");
                Log.i(TAG, data.toJSONString());
                if (data != null && data.size() > 0) {
                    TOPBAR_COLOR_NAMES = new String[data.size()];
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject jo = data.getJSONObject(i);
                        User user = JSON.parseObject(jo, User.class);
                        DATA_USER.add(user);
                        TOPBAR_COLOR_NAMES[i] = user.getName();
                    }
                }
                dismissProgressDialog();
            }
        });

        HttpRequest.getConfig(0, new OnHttpResponseListener() {
            @Override
            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                JSONObject jsonObject = JSON.parseObject(resultJson);
                JSONArray data = jsonObject == null ? null : jsonObject.getJSONArray("data");
                Log.i(TAG, data.toJSONString());
                if (data != null && data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject jo = data.getJSONObject(i);
                        CarConfig carConfig = JSON.parseObject(jo, CarConfig.class);
                        if (carConfig.getType().equals("1")) {
                            LIST_MODEL.add(carConfig);
                        } else if (carConfig.getType().equals("2")) {
                            LIST_NUMBER.add(carConfig);
                        } else if (carConfig.getType().equals("3")) {
                            LIST_MEASURES.add(carConfig);
                        }
                    }

                    if (LIST_MODEL != null && LIST_MODEL.size() > 0) {
                        TOPBAR_MODEL = new String[LIST_MODEL.size()];
                        for (int i = 0; i < LIST_MODEL.size(); i++) {
                            TOPBAR_MODEL[i] = LIST_MODEL.get(i).getName();
                        }
                    }
                    if (LIST_NUMBER != null && LIST_NUMBER.size() > 0) {
                        TOPBAR_NUMBER = new String[LIST_NUMBER.size()];
                        for (int i = 0; i < LIST_NUMBER.size(); i++) {
                            TOPBAR_NUMBER[i] = LIST_NUMBER.get(i).getName();
                        }
                    }
                    if (LIST_MEASURES != null && LIST_MEASURES.size() > 0) {
                        TOPBAR_MEASURES = new String[LIST_MEASURES.size()];
                        for (int i = 0; i < LIST_MEASURES.size(); i++) {
                            TOPBAR_MEASURES[i] = LIST_MEASURES.get(i).getName();
                        }
                    }

                }
            }
        });


        Calendar calendar = Calendar.getInstance();
        //获取系统的日期
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //获取系统时间
        //小时
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        //分钟
        int minute = calendar.get(Calendar.MINUTE);
        editCheckDate.setText(year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分");
        exhaustCheck.setCheckDate(year + "-" + month + "-" + day + "  " + hour + ":" + minute);


    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (! isPositive) {
            return;
        }

        switch (requestCode) {
            case 0:
                exhaustCheck.setCompany(editCompany.getText().toString());
                exhaustCheck.setCheckCompany(editCheckCompany.getText().toString());
                exhaustCheck.setJurisdiction(editJurisdiction.getText().toString());
                exhaustCheck.setPlateNumber(editPlateNumber.getText().toString());
                exhaustCheck.setModel(editModel.getText().toString());
                exhaustCheck.setCreationDate(editCreationDate.getText().toString());
                exhaustCheck.setMileage(editMileage.getText().toString());
                exhaustCheck.setPurify(editPurify.getText().toString());
                exhaustCheck.setSmoke1(editSmoke1.getText().toString());
                exhaustCheck.setSmoke2(editSmoke2.getText().toString());
                exhaustCheck.setSmoke3(editSmoke3.getText().toString());
                exhaustCheck.setSmoke4(editSmoke4.getText().toString());
                exhaustCheck.setRBAvg(editRBAvg.getText().toString());
                exhaustCheck.setKAvg(editKAvg.getText().toString());
                exhaustCheck.setMeter(editMeter.getText().toString());
                exhaustCheck.setRemarks(editRemarks.getText().toString());
                exhaustCheck.setCheckAddress(editCheckAddress.getText().toString());

                showProgressDialog(R.string.loading);

//                try {
//                    List<String> lsString = new ArrayList<>();

//                   final List<Boolean> lsBoo =new  ArrayList<>();
//                    for (int i = 0; i < paths.size(); i++) {
////                        lsString.add(FileUtils.encodeToString(paths.get(i)));
////                        Log.i(TAG, lsString.get(i));
//
//                        final int finalI = i;
//                        HttpRequest.uploadSign(FileUtils.encodeToString(paths.get(i)), 0, new OnHttpResponseListener() {
//                            @Override
//                            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                                JSONObject jsonObject = JSON.parseObject(resultJson);
//                                if (jsonObject.getBoolean("success")) {
//                                    bool = true;
//                                    pUrl = pUrl + jsonObject.getString("msg")+"|";
//                                } else {
//                                    bool = false;
//                                    showShortToast(jsonObject.getString("msg"));
//                                }
//                            }
//                        });
//                    }
                if(!pUrl.equals("") && pUrl.length() >0){
                    exhaustCheck.setPhoto(pUrl.substring(0,pUrl.length()-1));
                }else{
                    exhaustCheck.setPhoto("");
                }


                HttpRequest.submitExhaustCheck(exhaustCheck, 0, new OnHttpResponseListener() {
                    @Override
                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                        dismissProgressDialog();
                        JSONObject jsonObject = JSON.parseObject(resultJson);
                        if (jsonObject.getBoolean("success")) {
                            dismissProgressDialog();
                            //提交成功
                            showShortToast(R.string.add_succeed);
                            finish();
                        } else {
                            dismissProgressDialog();
                            showShortToast(jsonObject.getString("msg"));
                        }
                    }
                });
                break;
            default:
                break;
        }
    }


    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private int[] selectedDate = new int[]{1971, 0, 1};
    private String pUrl = "";
    private boolean bool = false;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                new AlertDialog(this, "提交记录", "确定表单是否填写完整并提交？", true, 0, this).show();

//                    HttpRequest.uploadFile(FileUtils.ListToString(lsString), 0, new OnHttpResponseListener() {
//                        @Override
//                        public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                            JSONObject jsonObject = JSON.parseObject(resultJson);
//                            if (jsonObject.getBoolean("success")) {
//                                Log.i("tag", jsonObject.getString("msg"));
//
//                                exhaustCheck.setPhoto(jsonObject.getString("msg"));
//
//                                HttpRequest.submitExhaustCheck(exhaustCheck, 0, new OnHttpResponseListener() {
//                                    @Override
//                                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
//                                        dismissProgressDialog();
//                                        JSONObject jsonObject = JSON.parseObject(resultJson);
//                                        if (jsonObject.getBoolean("success")) {
//                                            //提交成功
//                                            showShortToast(R.string.add_succeed);
//                                            finish();
//                                        } else {
//                                            showShortToast(jsonObject.getString("msg"));
//                                        }
//                                    }
//                                });
//
//
//                            } else {
//                                dismissProgressDialog();
//                                showShortToast(jsonObject.getString("msg"));
//                            }
//                            dismissProgressDialog();
//                        }
//                    });
//                } catch (FileNotFoundException e) {
//                    dismissProgressDialog();
//                    e.printStackTrace();
//                }

                break;

            case R.id.edit_testingPerson:
                if (TOPBAR_COLOR_NAMES != null && TOPBAR_COLOR_NAMES.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_COLOR_NAMES)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择检查人员"), REQUEST_TO_BOTTOM_PERSION1, false);
                }
                break;

            case R.id.edit_reviewer:
                if (TOPBAR_COLOR_NAMES != null && TOPBAR_COLOR_NAMES.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_COLOR_NAMES)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择检查人员"), REQUEST_TO_BOTTOM_PERSION2, false);
                }
                break;
            case R.id.edit_auditor:
                if (TOPBAR_COLOR_NAMES != null && TOPBAR_COLOR_NAMES.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_COLOR_NAMES)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择检查人员"), REQUEST_TO_BOTTOM_PERSION3, false);
                }
                break;
            case R.id.edit_creationDate:
                toActivity(DatePickerWindow.createIntent(context, new int[]{1971, 0, 1}
                        , TimeUtil.getDateDetail(System.currentTimeMillis())), REQUEST_TO_DATE_PICKER, false);
                break;
            case R.id.edit_carType:
                if (CAR_TYPE != null && CAR_TYPE.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, CAR_TYPE)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择车辆类型"), REQUEST_TO_CAR_TYPE, false);
                }
                break;
            case R.id.edit_instrument:
                if (TOPBAR_MODEL != null && TOPBAR_MODEL.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_MODEL)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择仪器型号"), REQUEST_TO_MODEL, false);
                }
                break;
            case R.id.edit_meter:
                if (TOPBAR_NUMBER != null && TOPBAR_NUMBER.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_NUMBER)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择仪表编号"), REQUEST_TO_NUMBER, false);
                }
                break;
            case R.id.edit_purify:
                if (TOPBAR_MEASURES != null && TOPBAR_MEASURES.length > 0) {
                    toActivity(BottomMenuWindow.createIntent(context, TOPBAR_MEASURES)
                            .putExtra(BottomMenuWindow.INTENT_TITLE, "选择净化措施"), REQUEST_TO_MEASURES, false);
                }
                break;
            case R.id.iv_driving_license:
//                selectPicture();

                Acp.getInstance(this).request(new AcpOptions.Builder()
                                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                                        , Manifest.permission.READ_PHONE_STATE
                                        , Manifest.permission.CAMERA)
                                /*以下为自定义提示语、按钮文字
                                .setDeniedMessage()
                                .setDeniedCloseBtn()
                                .setDeniedSettingBtn()
                                .setRationalMessage()
                                .setRationalBtn()*/
                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                Matisse.from(ExhaustCheckActivity.this)
                                        .choose(MimeType.ofAll(), false) // 选择 mime 的类型
                                        .capture(true)
                                        .captureStrategy(
                                                new CaptureStrategy(true, "soft.hb.activity.fileprovider"))
                                        .theme(R.style.Matisse_Dracula)
                                        .countable(true)
                                        .maxSelectable(1) // 图片选择的最多数量
                                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                        .thumbnailScale(0.85f) // 缩略图的比例
                                        .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                                        .forResult(REQUEST_CODE_CHOOSE1); // 设置作为标记的请求码
                            }

                            @Override
                            public void onDenied(List<String> permissions) {
                                showShortToast("没有拍照权限，请打开权限！");
                            }
                        });



                break;

            case R.id.clear:
                handWriteView.clear();
                break;
            case R.id.iv_sign:
                final Dialog dialog = new Dialog(this, R.style.Theme_Light_Dialog);
                View dialogView = LayoutInflater.from(this).inflate(R.layout.sign_dialog, null);
                //获得dialog的window窗口
                Window window = dialog.getWindow();
                //设置dialog在屏幕底部
                window.setGravity(Gravity.BOTTOM);
                //设置dialog弹出时的动画效果，从屏幕底部向上弹出
                window.setWindowAnimations(R.style.dialogStyle);
                window.getDecorView().setPadding(0, 0, 0, 0);
                //获得window窗口的属性
                android.view.WindowManager.LayoutParams lp = window.getAttributes();
                //设置窗口宽度为充满全屏
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                //设置窗口高度为包裹内容
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                //将设置好的属性set回去
                window.setAttributes(lp);
                //将自定义布局加载到dialog上
                dialog.setContentView(dialogView);
                handWriteView = (HandWriteView) dialogView.findViewById(R.id.view);
                dialogView.findViewById(R.id.clear).setOnClickListener(this);
                dialogView.findViewById(R.id.save).setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (handWriteView.isSign())
                            try {
                                showProgressDialog(R.string.loading);
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + new Date().getTime() + ".png";
                                handWriteView.save(path, true, 10, true);
                                HttpRequest.uploadSign(FileUtils.encodeToString(path), 0, new OnHttpResponseListener() {
                                    @Override
                                    public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                                        JSONObject jsonObject = JSON.parseObject(resultJson);
                                        if (jsonObject.getBoolean("success")) {
                                            exhaustCheck.setSign(jsonObject.getString("msg"));
                                            Glide.with(ExhaustCheckActivity.this).load(SettingUtil.URL_SERVER_IMG + jsonObject.getString("msg")).into(ivSign);
                                            dismissProgressDialog();
                                            dialog.dismiss();
                                        } else {
                                            dismissProgressDialog();
                                            dialog.dismiss();
                                            showShortToast(jsonObject.getString("msg"));
                                        }
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        else {
                            showShortToast("还没有签名！");
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.iv_photo1:
                Acp.getInstance(this).request(new AcpOptions.Builder()
                                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                                        , Manifest.permission.READ_PHONE_STATE
                                        , Manifest.permission.CAMERA)
                                /*以下为自定义提示语、按钮文字
                                .setDeniedMessage()
                                .setDeniedCloseBtn()
                                .setDeniedSettingBtn()
                                .setRationalMessage()
                                .setRationalBtn()*/
                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                Matisse.from(ExhaustCheckActivity.this)
                        .choose(MimeType.ofAll(), false) // 选择 mime 的类型
                        .capture(true)
                        .captureStrategy(
                                new CaptureStrategy(true, "soft.hb.activity.fileprovider"))
                        .theme(R.style.Matisse_Dracula)
                        .countable(true)
                        .maxSelectable(5) // 图片选择的最多数量
                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f) // 缩略图的比例
                        .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                        .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
                            }

                            @Override
                            public void onDenied(List<String> permissions) {
                                showShortToast("没有拍照权限，请打开权限！");
                            }
                        });
                break;
        }
    }


    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    private UriAdapter mAdapter;

    private static final int REQUEST_TO_BOTTOM_PERSION1 = 1;
    private static final int REQUEST_TO_BOTTOM_PERSION2 = 2;
    private static final int REQUEST_TO_BOTTOM_PERSION3 = 3;
    private static final int REQUEST_TO_DATE_PICKER = 33;
    private static final int REQUEST_TO_CAR_TYPE = 4;
    private static final int REQUEST_TO_SELECT_PICTURE = 20;
    private static final int REQUEST_TO_CUT_PICTURE = 21;
    private static final int REQUEST_TO_MODEL = 5;
    private static final int REQUEST_TO_NUMBER = 6;
    private static final int REQUEST_TO_MEASURES = 7;
    private static final int REQUEST_CODE_CHOOSE = 100;
    private static final int REQUEST_CODE_CHOOSE1 = 101;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_BOTTOM_PERSION1:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editTestingPerson.setText(DATA_USER.get(position).getName());
                        exhaustCheck.setTestingPerson(DATA_USER.get(position).getStrId());
                    }
                }
                break;
            case REQUEST_TO_BOTTOM_PERSION2:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editReviewer.setText(DATA_USER.get(position).getName());
                        exhaustCheck.setReviewer(DATA_USER.get(position).getStrId());
                    }
                }
                break;
            case REQUEST_TO_BOTTOM_PERSION3:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editAuditor.setText(DATA_USER.get(position).getName());
                        exhaustCheck.setAuditor(DATA_USER.get(position).getStrId());
                    }
                }
                break;
            case REQUEST_TO_DATE_PICKER:
                if (data != null) {
                    ArrayList<Integer> list = data.getIntegerArrayListExtra(DatePickerWindow.RESULT_DATE_DETAIL_LIST);
                    if (list != null && list.size() >= 3) {

                        selectedDate = new int[list.size()];
                        for (int i = 0; i < list.size(); i++) {
                            selectedDate[i] = list.get(i);
                        }
                        exhaustCheck.setCreationDate(selectedDate[0] + "-" + (selectedDate[1] + 1) + "-" + selectedDate[2]);
                        editCreationDate.setText(selectedDate[0] + "-" + (selectedDate[1] + 1) + "-" + selectedDate[2]);
                    }
                }
                break;
            case REQUEST_TO_CAR_TYPE:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editCarType.setText(CAR_TYPE[position]);
                        exhaustCheck.setCarType(CAR_TYPE[position]);
                    }
                }
                break;
            case REQUEST_TO_MODEL:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editInstrument.setText(TOPBAR_MODEL[position]);
                        exhaustCheck.setInstrument(TOPBAR_MODEL[position]);
                    }
                }
                break;
            case REQUEST_TO_NUMBER:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editMeter.setText(TOPBAR_NUMBER[position]);
                        exhaustCheck.setMeter(TOPBAR_NUMBER[position]);
                    }
                }
                break;
            case REQUEST_TO_MEASURES:
                if (data != null) {
                    int position = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (position >= 0) {
                        editPurify.setText(TOPBAR_MEASURES[position]);
                        exhaustCheck.setPurify(TOPBAR_MEASURES[position]);
                    }
                }
                break;
            case REQUEST_TO_SELECT_PICTURE:
                if (data != null) {
                    cutPicture(data.getStringExtra(SelectPictureActivity.RESULT_PICTURE_PATH));
                }
                break;
            case REQUEST_TO_CUT_PICTURE:
                if (data != null) {
                    setPicture(data.getStringExtra(CutPictureActivity.RESULT_PICTURE_PATH));
                }
                break;
            case REQUEST_CODE_CHOOSE:
                paths.addAll(Matisse.obtainPathResult(data));
                mAdapter.setData(paths, ExhaustCheckActivity.this);
                showProgressDialog(R.string.loading);
                for (int i = 0; i < paths.size(); i++) {
                    try {

                        HttpRequest.uploadSign(FileUtils.encodeToString(saveBitmap(this,getimage(paths.get(i)))), 0, new OnHttpResponseListener() {
                            @Override
                            public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                                JSONObject jsonObject = JSON.parseObject(resultJson);
                                dismissProgressDialog();
                                if (jsonObject.getBoolean("success")) {
                                    bool = true;
                                    pUrl = pUrl + jsonObject.getString("msg")+"|";
                                } else {
                                    bool = false;
                                    showShortToast(jsonObject.getString("msg"));
                                }
                            }
                        });
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;

            case REQUEST_CODE_CHOOSE1:
                if (data != null) {
                    setPicture(Matisse.obtainPathResult(data).get(0));
                }

                break;
        }
    }


    @Override
    public void finish() {
        super.finish();

    }

    @Override
    public void onHttpResponse(int requestCode, String resultJson, Exception e) {

    }


    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    private String picturePath;

    /**
     * 选择图片
     */
    private void selectPicture() {
        toActivity(SelectPictureActivity.createIntent(context), REQUEST_TO_SELECT_PICTURE, false);
    }

    /**
     * 裁剪图片
     *
     * @param path
     */
    private void cutPicture(String path) {
        if (StringUtil.isFilePath(path) == false) {
            android.util.Log.e(TAG, "cutPicture  StringUtil.isFilePath(path) == false >> showShortToast(找不到图片);return;");
            showShortToast("找不到图片");
            return;
        }
        this.picturePath = path;

        toActivity(CutPictureActivity.createIntent(context, path
                , DataKeeper.imagePath, "photo" + System.currentTimeMillis(), 300, 200)
                , REQUEST_TO_CUT_PICTURE);
    }

    /**
     * 显示图片
     *
     * @param path
     */
    private void setPicture(String path) {
        if (StringUtil.isFilePath(path) == false) {
            showShortToast("找不到图片");
            return;
        }

        this.picturePath = saveBitmap(this,getimage(path));
        showProgressDialog(R.string.loading);
        try {
            HttpRequest.uploadSign(FileUtils.encodeToString(this.picturePath), 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    if (jsonObject.getBoolean("success")) {
                        Glide.with(ExhaustCheckActivity.this).load(SettingUtil.URL_SERVER_IMG + jsonObject.getString("msg")).into(ivSrivingLicense);
                        exhaustCheck.setXinshizheng(jsonObject.getString("msg"));
                        Log.i("tag", exhaustCheck.getXinshizheng());
                        dismissProgressDialog();
                    } else {
                        dismissProgressDialog();
                        showShortToast(jsonObject.getString("msg"));
                    }
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
//        Glide.with(context).load(path).into(ivSrivingLicense);
    }


    private final String SD_PATH = "/sdcard/dskqxt/pic/";
    private final String IN_PATH = "/dskqxt/pic/";

    /**
     * 随机生产文件名
     *
     * @return
     */
    private String generateFileName() {
        return UUID.randomUUID().toString();
    }
    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public String saveBitmap(Context context, Bitmap mBitmap) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            savePath = SD_PATH;
        } else {
            savePath = context.getApplicationContext().getFilesDir()
                    .getAbsolutePath()
                    + IN_PATH;
        }
        try {
            filePic = new File(savePath + generateFileName() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }

        return filePic.getAbsolutePath();
    }


    private Bitmap compressPixel(String filePath) {
        Bitmap bmp = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //setting inSampleSize value allows to load a scaled down version of the original image
        options.inSampleSize = 2;

        //inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[16 * 1024];
        try {
            //load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp == null) {

                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(filePath);
                    BitmapFactory.decodeStream(inputStream, null, options);
                    inputStream.close();
                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        } finally {
            return bmp;
        }
    }

    private Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }

    private Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 90, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }




    public void showPopMenu(View view, final int pos) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.getMenuInflater().inflate(R.menu.menu_item, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                mAdapter.removeItem(pos);
                return false;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
//                Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
            }
        });
        popupMenu.show();
    }


    private static class UriAdapter extends RecyclerView.Adapter<UriAdapter.UriViewHolder> {

        private List<String> mPaths;
        private Context context;

        void setData(List<String> paths, Context context) {
            this.context = context;
            mPaths = paths;
            notifyDataSetChanged();
        }

        public void removeItem(int pos) {
            mPaths.remove(pos);
            notifyItemRemoved(pos);
            paths = this.mPaths;
            notifyDataSetChanged();
        }

        @Override
        public UriViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new UriViewHolder(
                    LayoutInflater.from(parent.getContext()).inflate(R.layout.uri_item, parent, false));
        }

        public interface OnItemOnClickListener {
            void onItemOnClick(View view, int pos);

            void onItemLongOnClick(View view, int pos);
        }

        private OnItemOnClickListener mOnItemOnClickListener;

        public void setOnItemClickListener(OnItemOnClickListener listener) {
            this.mOnItemOnClickListener = listener;
        }

        @Override
        public void onBindViewHolder(final UriViewHolder holder, final int position) {
            Glide.with(context).load(mPaths.get(position)).into(holder.mPath);
            holder.itemView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnItemOnClickListener.onItemOnClick(holder.itemView, position);
                }
            });

            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    mOnItemOnClickListener.onItemLongOnClick(holder.itemView, position);
                    return false;
                }
            });
        }

        @Override
        public int getItemCount() {
            return mPaths == null ? 0 : mPaths.size();
        }


        static class UriViewHolder extends RecyclerView.ViewHolder {

            private ImageView mPath;

            UriViewHolder(View contentView) {
                super(contentView);
                mPath = (ImageView) contentView.findViewById(R.id.iv_photo);

            }
        }
    }
}